﻿#include "itemedit.h"
#include "ui_itemedit.h"

ItemEdit::ItemEdit(QWidget *parent, int id, const QString &table) :
    QDialog(parent),
    _id(id),
    _table(table),
    ui(new Ui::ItemEdit)
{
    ui->setupUi(this);

    initView();
}

ItemEdit::~ItemEdit()
{
    delete ui;
}

void ItemEdit::initView()
{
    QSqlQuery query;
    QString sql=QString("select * from %1 where id=%2").arg(_table).arg(_id);
    query.exec(sql);
    if(query.next())
    {
        _label=query.value("label").toString();
        _detail=query.value("detail").toString();
        _addition=query.value("addition").toString();

        ui->label->setText(_label);
        ui->detail->setPlainText(_detail);
        if(!_addition.isEmpty())
            ui->addition->setText(_addition);
        else
            ui->addition->setVisible(false);
    }
}

bool ItemEdit::updateItem(const QString &label, const QString &detail, const QString &addition)
{
    QSqlQuery query;
    QString sql=QString("update %1 set label='%2',detail='%3',addition='%4' where id=%5")
            .arg(_table)
            .arg(label)
            .arg(detail)
            .arg(addition)
            .arg(_id);

    if(query.exec(sql))
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void ItemEdit::on_btn_save_clicked()
{
    QString label=ui->label->text().trimmed();
    if(label.isEmpty())
        return;

    QString detail=ui->detail->toPlainText();
    if(detail.isEmpty())
        return;

    QString addition{};
    if(ui->addition->isVisible())
        addition=ui->addition->text().trimmed();

    if(label == _label && detail == _detail && addition == _addition)
    {
        close();
        return;
    }

    if(updateItem(label,detail,addition))
        accept();
    else
        QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("无法保存数据！"));
}
